package info.m3o.jsonicposter2010;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

//Import jsonic
//This sample program was tested with jsonic-1.1.3.jar
import net.arnx.jsonic.JSON;  

//This code is based on http://www.atmarkit.co.jp/fjava/javatips/069java006.html
public class MainClass {

  public static void main(String args[]) throws Exception {
    // String query = "name=yourname&email=youremail@yourserver.com";

    MyKeyPass mykeypass = new MyKeyPass();
    // Make a JSON encoded object/string.
    String query = JSON.encode(mykeypass, true);

    // String urlString = "http://localhost:8080/jsp-examples/post.jsp";
    String urlString = "http://devquiz.appspot.com/personalpost";

    try {
      URL url = new URL(urlString);
      URLConnection uc = url.openConnection();
      uc.setDoOutput(true);// enable POST

      // When you don't need to set the header, comment out following lines.
      // uc.setRequestProperty("User-Agent",
      // "@IT java- tips URLConnection");
      // uc.setRequestProperty("Accept-Language", "ja");

      // get OutputStream for POST
      OutputStream os = uc.getOutputStream();

      PrintStream ps = new PrintStream(os);

      // POST data
      ps.print(query);
      ps.close();

      // Obtain the POST result
      InputStream is = uc.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      String s;
      while ((s = reader.readLine()) != null) {
        System.out.println(s);
      }
      reader.close();
    } catch (MalformedURLException e) {
      System.err.println("Invalid URL format: " + urlString);
      System.exit(-1);
    } catch (IOException e) {
      System.err.println("Can't connect to " + urlString);
      System.exit(-1);
    }

  }
}
